<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: xajax.checkout.php 277 2013-09-23 08:55:35Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 277 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-23 08:55:35 +0000 (Mon, 23 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     neommerce - www.neommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

function checkout_check() {
	$ajax = new xajaxResponse();

	if (empty($_SESSION['customer_id']))
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");

	else {
		global $order;
		global $checkout;
		global $price;

		$order = new order();
		require (DIR_WS_CLASSES.'class.shipping.php');
		$shipping_modules = new shipping();
		$chkt_error = '';

		if(empty($_SESSION['shipping']) && $checkout->isVirtual() != 1 && $checkout->isFreeShipping($order, $price) == false && (not_null(MODULE_SHIPPING_INSTALLED)))
			$chkt_error .= '- '.CHECKOUT_NO_SHIPPING_MODULE_SELECTED."\n";

		if(empty($_SESSION['payment']) && (not_null(MODULE_PAYMENT_INSTALLED)))
			$chkt_error .= '- '.CHECKOUT_NO_PAYMENT_MODULE_SELECTED."\n";

		if(!empty($chkt_error)) {
			$ajax->alert($chkt_error);
			$ajax->call('removeAnimation()');
			
		} elseif(empty($chkt_error))
			$ajax->script("$('#checkout').submit();");

	}
	return $ajax;
}

function useGV($yn) {
	$ajax = new xajaxResponse();

	if(empty($_SESSION['customer_id']))
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");

	else {
		global $price;
		global $order;
		global $checkout;
		global $order_total_modules;
		
		$real_total = $order->info['total'];
		
		if($yn == 1) {
			$_SESSION['cot_gv'] = true;
			if(!empty($_SESSION['payment']) && $_SESSION['payment'] != 'no_payment')
				$_SESSION['old_payment'] = $_SESSION['payment'];

		} else {
			if(!empty($_SESSION['old_payment'])) {
				$_SESSION['payment'] = $_SESSION['old_payment'];
				unset($_SESSION['old_payment']);
			}
			$_SESSION['cot_gv'] = false;
			$order_total_modules = new order_total;
			while (list (, $value) = each($order_total_modules->modules)) {
				$class = substr($value, 0, strrpos($value, '.'));
				if($GLOBALS['ot_gv']->enabled && $GLOBALS['ot_gv']->credit_class)
					$ajax->assign($GLOBALS['ot_gv']->code.'_amount', 'innerHTML', $GLOBALS['ot_gv']->getAmount());
			}
		}
		$order = new order();
		$order_total_modules = new order_total();
		$order_total_modules->process();

		if($order->info['total'] <= 0)
			if(!empty($_SESSION['old_payment']))
				unset($_SESSION['payment']);

		$order = new order();
		$order_total_modules = new order_total();
		$order_total_modules->process();
		
		if($order->info['total'] <= 0)
			if(!empty($_SESSION['old_payment']))
				$_SESSION['payment'] = $_SESSION['old_payment'];

		if($order->info['total'] <= 0)
			$_SESSION['payment'] = 'no_payment';

		$virtual = $checkout->isVirtual();
		$payment_modules = new payment();
		$payment_modules->update_status();

		$payment_button = '';
		$payment_button .= str_replace("\n","",$payment_modules->process_button(true));
		
		if(isset($_SESSION['cot_gv']) && $_SESSION['cot_gv'] == true) {
			reset($order_total_modules->modules);
			
			while (list (, $value) = each($order_total_modules->modules)) {
				$class = substr($value, 0, strrpos($value, '.'));

				if($GLOBALS['ot_gv']->enabled && $GLOBALS['ot_gv']->credit_class) {
					$rest = $GLOBALS['ot_gv']->getAmount(false)-$real_total;
					$ajax->assign($GLOBALS['ot_gv']->code.'_amount', 'innerHTML', $price->Format(($rest > 1 ? $rest : 0), true)); 
				}
			}
		}
		
		if($order->info['total'] <= 0) {
			$form_url = $checkout->getFormUrl();
			$ajax->script("$('#payment_modules').hide();
						  $('#payment_gccover').show();
						  $('#loader_payment_modules').hide();
						  $('#checkout').attr('action', '$form_url');
						  $('#checkout_hiddens').html('$payment_button').show();
						  $('#checkout_error_payment').hide();
						  $('#checkout_error_payment').html('');
						  if($('#btn_payment_modules').html() == '-')
						  	showFromStart('payment_modules')");

		} else {
			$form_url = $checkout->getFormUrl();
			$ajax->script("$('#payment_modules').show();
						  $('#payment_gccover').hide();
						  $('#loader_payment_modules').hide();
						  $('#checkout').attr('action','$form_url');
						  $('#checkout_hiddens').html('$payment_button');
						  if($('#btn_payment_modules').html() == '-') 
						  	showFromStart('payment_modules')");
		}
		if($virtual == 1)
			$ajax->script("updateBecauseItsVirtual();");

		else {
			if($checkout->isFreeShipping($order, $price))
				$ajax->script("updateBecauseItsFreeShipping();");
			else
				$ajax->script("updateBecauseItsNotFreeShipping();");
		}
		$ajax->assign("checkout_total", "innerHTML", $checkout->getTotalBlock($order, $order_total_modules, $price));
	}
	return $ajax;
}

function updatePaymentModule($vars) {
	$ajax = new xajaxResponse();
	if(empty($_SESSION['customer_id']))
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");
	else {
		global $checkout;
		global $order;
		global $price;
		global $order_total_modules;

		$_SESSION['checkout_payment_error'] = '';
		$vars = $checkout->convertToVars($vars);
		$_SESSION['payment'] = $vars['payment'];
		if(isset ($_SESSION['credit_covers']))
			$_SESSION['payment'] = 'no_payment';

		$order = new order();
		$order_total_modules = new order_total();
		$order_total_modules->process();
		$payment_modules = new payment($_SESSION['payment']);
		$payment_modules->update_status();
		$payment_modules->pre_confirmation_check($vars);
		$payment_button = '';
		$payment_button .= str_replace("\n","",$payment_modules->process_button(false, $vars));

		$form_url = $checkout->getFormUrl();
		if($_SESSION['checkout_payment_error'] != '') {
			unset($_SESSION['payment']);
			$perror = $checkout->convertToVars($_SESSION['checkout_payment_error']);
			$ajax->script("$('#payment_module_error').html('".$perror['error']."').show()");
			$ajax->script("activatePayment('no');");

		} else {

			if($_SESSION['stat_luupws'] == 1 || $_SESSION['payment'] != 'luupws') 
				$ajax->script("activatePayment('prow_".$_SESSION['payment']."');");
			if($_SESSION['stat_luupws'] != 1 && $_SESSION['payment'] == 'luupws') 
				$ajax->script("activatePayment('no');");
			if($_SESSION['stat_luupws'] == 1 || $_SESSION['payment'] != 'luupws') {
				$ajax->script("$('#payment_module_error').html('<span class=\"module_ok\">".CHECKOUT_PAYMENT_OK."</span>').show();
							  $('#shipping_module_error').html('');
							  $('#checkout_hiddens').html('$payment_button').show();
							  $('#button_save_payment').removeClass('pulsate');");
			}
		}
		if($order->info['total'] <= 0) {
			if(!empty($_SESSION['payment']) && $_SESSION['payment'] != 'no_payment') {
					$_SESSION['old_payment'] = $_SESSION['payment'];
					$_SESSION['payment'] = 'no_payment';
			}
			$order = new order();
			$order_total_modules = new order_total();
			$order_total_modules->process();
			$form_url = $checkout->getFormUrl();
			$ajax->script("$('#payment_modules').hide(); $('#payment_gccover').show();");
		}
		$ajax->script("$('#loader_payment_modules').hide();
					  makeActive('form_payment_modules');
					  showFromStart('payment_modules');
					  $('#checkout').attr('action', '$form_url');
					  clearBlinkBlink('payment');
					  if($('#btn_shipping_modules').html() == '-') 
					  	showFromStart('shipping_modules');");

		$ajax->assign("checkout_total", "innerHTML", $checkout->getTotalBlock($order, $order_total_modules, $price));
	}
	return $ajax;
}

function updateShippingModule($vars) {
	global $db;
	$ajax = new xajaxResponse();

	if(empty($_SESSION['customer_id']))
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");

	else {
		global $checkout;
		global $order;
		global $price;
		global $total_weight;
		global $total_count;
		global $order_total_modules;
				
		$total_weight = $_SESSION['cart']->show_weight();
		$total_count = $_SESSION['cart']->count_contents();

		require (DIR_WS_CLASSES.'class.shipping.php');
		$shipping_modules = new shipping();
		$vars = $checkout->convertToVars($vars);
		
		$_SESSION['shipping'] = $vars['shipping'];
		list ($module, $method) = explode('_', $_SESSION['shipping']);
		
		if(!empty($module) || ($_SESSION['shipping'] == 'free_free')) {
			if($_SESSION['shipping'] == 'free_free') {
				$quote[0]['methods'][0]['title'] = FREE_SHIPPING_TITLE;
				$quote[0]['methods'][0]['cost'] = '0';
			} else
				$quote = $shipping_modules->quote($method, $module);

			if(isset($quote['error']))
				unset ($_SESSION['shipping']);
			else {
				if((isset($quote[0]['methods'][0]['title'])) && (isset($quote[0]['methods'][0]['cost'])))
					$_SESSION['shipping'] = array('id' => $_SESSION['shipping'],
													'title' => (($checkout->isFreeShipping($order, $price) == true) ? $quote[0]['methods'][0]['title'] : $quote[0]['module'].' ('.$quote[0]['methods'][0]['title'].')'),
													'cost' => $quote[0]['methods'][0]['cost']);
			}
			
		} else
			unset($_SESSION['shipping']);

		$order = new order();
		$order_total_modules = new order_total();
		$order_total_modules->process();
		$payment_modules = new payment();
		$payment_modules->update_status();

		$payment_button = '';
		$payment_button .= str_replace("\n","",$payment_modules->process_button(true));

		global $payment_compatible;
		$payment_compatible = true;
		$payment_block = $checkout->getPaymentBlock($price, $payment_modules);

		$form_url = $checkout->getFormUrl();

		$ajax->script("activateShipping('srow".($vars[$vars['shipping'].'_num']-1)."');");
		$ajax->script("$('#shipping_module_error').html('<span class=\"module_ok\">".CHECKOUT_SHIPPING_OK."</span>').show(); $('#payment_module_error').html('');");
		
		if(!$payment_compatible)
			$ajax->script("$('#payment_module_error').html('".CHECKOUT_PAYMENT_NOT_COMPATIBLE."').show()");
			
		if($order->info['total'] <= 0) {
			if(!empty($_SESSION['payment']) && $_SESSION['payment'] != 'no_payment') {
				$_SESSION['old_payment'] = $_SESSION['payment'];
				$_SESSION['payment'] = 'no_payment';
			}
			$order = new order();
			$order_total_modules = new order_total();
			$order_total_modules->process();
			$form_url = $checkout->getFormUrl();
			$ajax->script("$('#payment_modules').hide();$('#payment_gccover').show();");
		}
		$ajax->assign("payments","innerHTML",$payment_block);
		$ajax->script("$('#loader_shipping_modules').hide();
					  makeActive('form_shipping_modules');
					  $('#checkout').attr('action', '$form_url');
					  showFromStart('shipping_modules');
					  if($('#btn_payment_modules').html() == '-') 
					  	setTimeout(\"showFromStart('payment_modules')\", 650);
					  $('#checkout_hiddens').html('$payment_button').show();
					  clearBlinkBlink('shipping');");

		$ajax->assign("checkout_total","innerHTML",$checkout->getTotalBlock($order, $order_total_modules, $price));
	}
	return $ajax;
}

function updateProducts($id, $math) {
	$ajax = new xajaxResponse();
	return $ajax; //turn off


	if(empty($_SESSION['customer_id']))
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");

	else {
		global $price;
		global $db;
		global $order;
		global $checkout;
		global $total_weight;
		global $total_count;
		global $shipping_modules;
		global $order_total_modules;

		unset($_SESSION['actual_content']);

		$qty_now = (int)$_SESSION['cart']->get_quantity($id);

		if($math == 'plus') {
			if($qty_now >= MAX_PRODUCTS_QTY)
				$qty_new = MAX_PRODUCTS_QTY;
			else
				$qty_new = $qty_now+1;
		} elseif($math == 'minus') {
			if($qty_now <= 1)
				$qty_new = $qty_now;
			else
				$qty_new = $qty_now-1;
		}

		if(STOCK_CHECK == 'true' && STOCK_ALLOW_CHECKOUT != 'true')
			$stock_check = true;

		if(ATTRIBUTE_STOCK_CHECK == 'true' && STOCK_ALLOW_CHECKOUT != 'true')
			$attribute_stock_check = true;

		$count_error_attributes = 0;

		$real_product_id = substr($id, 0, strpos($id, '{'));
		$attributes_string = substr($id, strpos($id, '{'));
		$attributes_sub_arr = explode('{',$attributes_string);
		$options = array();
		$values = array();
		for ($a=0; $a<count($attributes_sub_arr); $a++) {
			if(strlen($attributes_sub_arr[$a]) > 2) {
				$attributes_main_arr = explode('}', $attributes_sub_arr[$a]);
				array_push($options, $attributes_main_arr[0]);
				$attribute_value = $db->db_query("SELECT
															products_options_value_id
														FROM
															".TABLE_CUSTOMERS_BASKET_ATTRIBUTES."
														WHERE
															customers_id = '".$_SESSION['customer_id']."'
														AND
															products_id = '".$id."'
														AND
															products_options_id = '".$attributes_main_arr[0]."'");

				array_push($values, $attribute_value->fields['products_options_value_id']);
			}
		}

		for ($b = 0; $b < count($options); $b++) {
			$select_attributes_id = $db->db_query("SELECT
															products_attributes_id
														FROM
															".TABLE_PRODUCTS_ATTRIBUTES."
														WHERE
															products_id = '".$real_product_id."'
														AND
															options_id = '".$options[$b]."'
														AND
															options_values_id = '".$values[$b]."'");

			if(check_stock_attributes($select_attributes_id->fields['products_attributes_id'], $qty_new) != '')
				$count_error_attributes++;
		}

		if(($stock_check ? (check_stock($id, $qty_new) != '') : false) || ($attribute_stock_check ? ($count_error_attributes > 0) : false)) {
			$ajax->script("$('#loader_products').hide();
							alert('".html_entity_decode(CHECKOUT_OUT_OF_STOCK)."');");

		} else {
			$_SESSION['cart']->update_quantity($id, $qty_new, $_SESSION['cart']->contents[$id]['attributes']);
			$order = new order();
			$price_new = 0;
			$tax_class_id = $checkout->getTaxID($id);
			
			$single_price_new = $price->GetPrice($id, false, 1, $tax_class_id, '')+$price->format($_SESSION['cart']->attributes_price($id), false);
			$price_new = ($price->GetPrice($id, false, 1, $tax_class_id, '')*$qty_new)+$price->format($_SESSION['cart']->attributes_price($id), false);

			$total_weight = $_SESSION['cart']->show_weight();
			$total_count = $_SESSION['cart']->count_contents();

			if(!empty($_SESSION['shipping']['id'])) {
				list($module, $method) = explode('_', $_SESSION['shipping']['id']);
				if(!is_object($shipping_modules)) {
					require (DIR_WS_CLASSES.'class.shipping.php');
					$shipping_modules = new shipping();
				}
				$quote = $shipping_modules->quote($method, $module);
				$_SESSION['shipping']['cost'] = $quote[0]['methods'][0]['cost'];
			}
			$order = new order();
			$shipping_block = $checkout->getShippingBlock($price);
			$order = new order();
			$virtual = $checkout->isVirtual();
			$order_total_modules = new order_total();
			$order_total_modules->process();
			$payment_modules = new payment();
			$payment_modules->update_status();

			$payment_button = str_replace("\n","",$payment_modules->process_button(true));
			
			global $payment_compatible;
			$payment_compatible = true;
			$payment_block = $checkout->getPaymentBlock($price, $payment_modules);

			if($virtual == 1)
				$ajax->script("updateBecauseItsVirtual();");
			
			if($checkout->isFreeShipping($order, $price))
				$ajax->script("updateBecauseItsFreeShipping();");
			else
				$ajax->script("updateBecauseItsNotFreeShipping();");

			if($order->info['total'] <= 0) {
				if(!empty($_SESSION['payment']) && $_SESSION['payment'] != 'no_payment') {
					$_SESSION['old_payment'] = $_SESSION['payment'];
					$_SESSION['payment'] = 'no_payment';
				}
				$order = new order();
				$order_total_modules = new order_total();
				$order_total_modules->process();
				$form_url = $checkout->getFormUrl();

				$ajax->script("$('#payment_modules').hide();
							  $('#payment_gccover').show();
					  		  $('#checkout').attr('action', '$form_url');
							  if($('#btn_payment_modules').html() == '-') 
							  	showFromStart('payment_modules')");

			} else {
				if(!empty($_SESSION['old_payment'])) {
					$_SESSION['payment'] = $_SESSION['old_payment'];
					unset($_SESSION['old_payment']);
					$order = new order();
					$order_total_modules = new order_total();
					$order_total_modules->process();
				}
				$form_url = $checkout->getFormUrl();
				$ajax->script("$('#payment_modules').show();
							  $('#payment_gccover').hide();
					  		  $('#checkout').attr('action', '$form_url');
							  if($('#btn_payment_modules').html() == '-')
							  	showFromStart('payment_modules')");
			}
			
			$shippings_count = count_shipping_modules();

			$ajax->assign("payments", "innerHTML",$payment_block);
			$ajax->assign("shippings", "innerHTML", $shipping_block);
			$ajax->assign("qty_$id", "innerHTML", $qty_new);
			$ajax->assign("single_price_$id", "innerHTML", $price->format($single_price_new, true));
			$ajax->assign("price_$id", "innerHTML", $price->format($price_new, true));
			$ajax->assign("checkout_products_howmuch", "innerHTML", $_SESSION['cart']->count_contents());
			$ajax->script("$('#loader_products').hide();
						  showFromStart('products');
						  $('#checkout_hiddens').html('$payment_button').show();
						  $('#shipping_module_error').html('');
						  $('#payment_module_error').html('');
						  if($('#btn_shipping_modules').html() == '-') showFromStart('shipping_modules');
						  smodule_length = $shippings_count;");
			$ajax->assign("checkout_total","innerHTML",$checkout->getTotalBlock($order, $order_total_modules, $price));
		}
	}
	return $ajax;
}

function removeProduct($id) {
	$ajax = new xajaxResponse();
	if(empty($_SESSION['customer_id'])) {
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");
	} else {
		global $checkout;
		global $order;
		global $price;
		global $total_weight;
		global $total_count;
		global $shipping_modules;
		global $order_total_modules;
		unset($_SESSION['actual_content']);

		$_SESSION['cart']->remove($id);
		$_SESSION['cart']->restore_contents();

		if($_SESSION['cart']->count_contents() > 0) {

			$order = new order();

			$total_weight = $_SESSION['cart']->show_weight();
			$total_count = $_SESSION['cart']->count_contents();

			if(!empty($_SESSION['shipping']['id'])) {
				list ($module, $method) = explode('_', $_SESSION['shipping']['id']);
				if(!is_object($shipping_modules)) {
					require (DIR_WS_CLASSES.'class.shipping.php');
					$shipping_modules = new shipping();
				}
				$quote = $shipping_modules->quote($method, $module);
				$_SESSION['shipping']['cost'] = $quote[0]['methods'][0]['cost'];
			}
			$order = new order();
			$shipping_block = $checkout->getShippingBlock($price);
			$order = new order();
			$virtual = $checkout->isVirtual();
			$order_total_modules = new order_total();
			$order_total_modules->process();
			$payment_modules = new payment();
			$payment_modules->update_status();

			$payment_button = '';
			$payment_button .= str_replace("\n","",$payment_modules->process_button(true));

			global $payment_compatible;
			$payment_compatible = true;
			$payment_block = $checkout->getPaymentBlock($price, $payment_modules);

			if($order->info['total'] <= 0) {
				if(!empty($_SESSION['payment']) && $_SESSION['payment'] != 'no_payment') {
					$_SESSION['old_payment'] = $_SESSION['payment'];
					$_SESSION['payment'] = 'no_payment';
				}
				$order = new order();
				$order_total_modules = new order_total();
				$order_total_modules->process();
				$form_url = $checkout->getFormUrl();

				$ajax->script("$('#payment_modules').hide();
							  $('#payment_gccover').show();
					  		  $('#checkout').attr('action', '$form_url');
							  if($('#btn_payment_modules').html() == '-') { showFromStart('payment_modules') }");

			} else {
				if(!empty($_SESSION['old_payment'])) {
					$_SESSION['payment'] = $_SESSION['old_payment'];
					unset($_SESSION['old_payment']);
					$order = new order();
					$order_total_modules = new order_total();
					$order_total_modules->process();
				}
				$form_url = $checkout->getFormUrl();
				$ajax->script("$('#payment_modules').show();
							  $('#payment_gccover').hide();
					  		  $('#checkout').attr('action', '$form_url');
							  if($('#btn_payment_modules').html() == '-') { showFromStart('payment_modules') }");
			}

			$shippings_count = count_shipping_modules();
			$ajax->assign("shippings", "innerHTML", $shipping_block);
			$ajax->assign("payments", "innerHTML", $payment_block);
			$ajax->assign("product_$id", "innerHTML", '');
			$ajax->assign("checkout_products_howmuch","innerHTML", $_SESSION['cart']->count_contents());
			$ajax->script("$('#loader_products').hide();
						  $('#product_$id').remove();
						  showFromStart('products');
						  $('#checkout_hiddens').html('$payment_button').show();
						  $('#shipping_module_error').html('');
						  $('#payment_module_error').html('');
						  if($('#btn_shipping_modules').html() == '-') showFromStart('shipping_modules');
						  if($('#btn_shipping_address').html() == '-') showFromStart('shipping_address');
						  smodule_length = $shippings_count;");

			if($virtual == 1)
				$ajax->script("updateBecauseItsVirtual();");
			else {
				if($checkout->isFreeShipping($order, $price))
					$ajax->script("updateBecauseItsFreeShipping();");
				else
					$ajax->script("updateBecauseItsNotFreeShipping();");
			}
			$ajax->assign("checkout_total", "innerHTML", $checkout->getTotalBlock($order, $order_total_modules, $price));

		} else {
			$ajax->assign("product_$id", "innerHTML", CHECKOUT_EMPTY_CART);
			$ajax->script("$('#loader_products').hide();
						  window.location.href = '".FILENAME_SHOPPING_CART."';
						  showFromStart('products');");
		}
	}
	return $ajax;
}

function updateAttributes($html_id, $html_aid, $att_string) {
	$ajax = new xajaxResponse();

	if(empty($_SESSION['customer_id'])) {
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");

	} else {
		global $db;
		global $price;
		global $order;
		global $checkout;
		global $total_count;
		global $total_weight;
		global $shipping_modules;
		global $order_total_modules;
		unset($_SESSION['actual_content']);

		$att_array = explode('|',$att_string);
		$old_att = $db->db_query("SELECT
										products_options_value_id
									FROM
										".TABLE_CUSTOMERS_BASKET_ATTRIBUTES."
									WHERE
										products_options_id = '".$att_array[1]."'
									AND
										products_id = '".$att_array[0]."'");

		$db->db_query("UPDATE
							".TABLE_CUSTOMERS_BASKET_ATTRIBUTES."
						SET
							products_options_value_id = '".$att_array[2]."'
						WHERE
							products_options_id = '".$att_array[1]."'
						AND
							products_id = '".$att_array[0]."'");

		$_SESSION['cart']->restore_contents();

		if(STOCK_CHECK == 'true' && STOCK_ALLOW_CHECKOUT != 'true')
			$stock_check = true;

		if(ATTRIBUTE_STOCK_CHECK == 'true' && STOCK_ALLOW_CHECKOUT != 'true')
			$attribute_stock_check = true;

		$attribute_id = $db->db_query("SELECT
											products_attributes_id
										FROM
											".TABLE_PRODUCTS_ATTRIBUTES."
										WHERE
											options_values_id = '".$att_array[2]."'");

		if(($stock_check ? (check_stock($att_array[0], $_SESSION['cart']->contents[$att_array[0]]['qty']) != '') : false) || ($attribute_stock_check ? (check_stock_attributes($attribute_id->fields['products_attributes_id'], $_SESSION['cart']->contents[$att_array[0]]['qty']) != '') : false)) {

			$db->db_query("UPDATE
								".TABLE_CUSTOMERS_BASKET_ATTRIBUTES."
							SET
								products_options_value_id = '".$old_att->fields['products_options_value_id']."'
							WHERE
								products_options_id = '".$att_array[1]."'
							AND
								products_id = '".$att_array[0]."'");

			$_SESSION['cart']->restore_contents();

			$new_value = $att_array[0].'|'.$att_array[1].'|'.$old_att;

			$ajax->script("$('#loader_products').hide();
						  alert('".html_entity_decode(CHECKOUT_OUT_OF_STOCK)."');
						  $('#$html_id').value = '$new_value';
						  $('#$html_id').disabled = false;");
		} else {

			$price_new = 0;
			$tax_class_id = $checkout->getTaxID($att_array[0]);

			$price_new = $price->GetPrice($att_array[0], false, $_SESSION['cart']->contents[$att_array[0]]['qty'], $tax_class_id,'')+$price->format($_SESSION['cart']->attributes_price($att_array[0]), false);
			$price_new *= $_SESSION['cart']->contents[$att_array[0]]['qty'];
						
			$row = $db->db_query("SELECT
										products_options_values_name
									FROM
										".TABLE_PRODUCTS_OPTIONS_VALUES."
									WHERE
										language_id = '".$_SESSION['languages_id']."'
									AND
										products_options_values_id = '".$att_array[2]."'");

			$order = new order();

			$total_weight = $_SESSION['cart']->show_weight();
			$total_count = $_SESSION['cart']->count_contents();

			if(!empty($_SESSION['shipping']['id'])) {
				list ($module, $method) = explode('_', $_SESSION['shipping']['id']);
				if(!is_object($shipping_modules)) {
					require (DIR_WS_CLASSES.'class.shipping.php');
					$shipping_modules = new shipping();
				}
				$quote = $shipping_modules->quote($method, $module);
				$_SESSION['shipping']['cost'] = $quote[0]['methods'][0]['cost'];
			}

			$virtual = $checkout->isVirtual();
			$order = new order();
			$shipping_block = $checkout->getShippingBlock($price);
			$order = new order();
			$order_total_modules = new order_total();
			$order_total_modules->process();
			$payment_modules = new payment();
			$payment_modules->update_status();

			$payment_button = '';
			$payment_button .= str_replace("\n","",$payment_modules->process_button(true));

			global $payment_compatible;
			$payment_compatible = true;
			$payment_block = $checkout->getPaymentBlock($price, $payment_modules);

			if($virtual == 1)
				$ajax->script("updateBecauseItsVirtual();");
			else {
				if($checkout->isFreeShipping($order, $price)) {
					$ajax->script("updateBecauseItsFreeShipping();");
				}  else {
					$ajax->script("updateBecauseItsNotFreeShipping();");
				}
			}
			if($order->info['total'] <= 0) {
				if(!empty($_SESSION['payment']) && $_SESSION['payment'] != 'no_payment') {
					$_SESSION['old_payment'] = $_SESSION['payment'];
					$_SESSION['payment'] = 'no_payment';
				}
				$order = new order();
				$order_total_modules = new order_total();
				$order_total_modules->process();
				$form_url = $checkout->getFormUrl();

				$ajax->script("$('#payment_modules').hide();
							  $('#payment_gccover').show();
					  		  $('#checkout').attr('action', '$form_url');
							  if($('#btn_payment_modules').html() == '-') { showFromStart('payment_modules') }");

			} else {
				if(!empty($_SESSION['old_payment'])) {
					$_SESSION['payment'] = $_SESSION['old_payment'];
					unset($_SESSION['old_payment']);
					$order = new order();
					$order_total_modules = new order_total();
					$order_total_modules->process();
				}
				$form_url = $checkout->getFormUrl();
				$ajax->script("$('#payment_modules').show();
							  $('#payment_gccover').hide();
					  		  $('#checkout').attr('action', '$form_url');
							  if($('#btn_payment_modules').html() == '-') { showFromStart('payment_modules') }");
			}

			$shippings_count = count_shipping_modules();
			$ajax->assign("shippings", "innerHTML", $shipping_block);
			$ajax->assign("payments", "innerHTML", $payment_block);
			$ajax->assign("attt_$html_aid","innerHTML", html_entity_decode($row->fields['products_options_values_name']));
			$ajax->assign("price_".$att_array[0],"innerHTML", $price->format($price_new, true));
			$ajax->script("$('#loader_products').hide();
							$('#atta_$html_aid').show();
							$('#attd_$html_aid').hide();
							showFromStart('products');
							$('#checkout_hiddens').html('$payment_button').show();
							$('#shipping_module_error').html('');
							$('#payment_module_error').html('');
							if($('#btn_shipping_modules').html() == '-') showFromStart('shipping_modules');
							smodule_length = $shippings_count;");
			$ajax->assign("checkout_total","innerHTML", $checkout->getTotalBlock($order, $order_total_modules, $price));
		}
	}
	return $ajax;
}

function updateAddressSelect($which) {
	$ajax = new xajaxResponse();

	if(empty($_SESSION['customer_id']))
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");

	else {
		global $checkout;
		$ajax->assign("dyn_".$which."_address", "innerHTML", $checkout->getAddresses($which));
		$ajax->script("$('#".$which."_address_select').show();
		$('#".$which."_address').hide();
		$('#".$which."_address_button_edit').hide();
		$('#".$which."_address_button_save').show();
		makeActive('chkt_".$which."_address');
		$('#loader_".$which."_address').hide();
		showFromStart('".$which."_address');");
	}
	return $ajax;
}

function updateAddressBySelect($which, $id) {
	$ajax = new xajaxResponse();

	if(empty($_SESSION['customer_id']))
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");

	else {
		global $order;
		global $checkout;
		global $price;
		global $order_total_modules;

		if($which == 'shipping') {
			$sess = 'sendto';
		} elseif($which == 'payment') {
			$sess = 'billto';
		}
		$_SESSION[$sess] = (int)$id;

		if($which == 'shipping') {
			$price = new price($_SESSION['currency'], $_SESSION['customers_status']['customers_status_id']);
			$order = new order();
			$zone_change = false;
			if($_SESSION['delivery_zone'] != $order->delivery['country']['iso_code_2'])
				$zone_change = true;

			$_SESSION['delivery_zone'] = $order->delivery['country']['iso_code_2'];

      if($checkout->isFreeShipping($order, $price)) {
        $ajax->assign("free_shipping_modules", "innerHTML", ' ');
        //$ajax->script("updateBecauseItsFreeShipping();");
      }
      else {
        include_once(DIR_WS_LANGUAGES.$_SESSION['language'].'/modules/shipping/freeamount.php');
        $ajax->assign("free_shipping_modules", "innerHTML", sprintf(FREE_SHIPPING_DESCRIPTION, $price->format($price->_ext->getFreeShippingAmount(), true, 0, true)).draw_hidden_field('shipping', 'free_free'));
        //$ajax->script("updateBecauseItsNotFreeShipping();");
      }

			$product_ids = explode(', ',$_SESSION['cart']->get_product_id_list());

			for ($b=0; $b<count($product_ids); $b++) {
				$tax_class_id = $checkout->getTaxID($product_ids[$b]);
				$product_qty = $_SESSION['cart']->contents[$product_ids[$b]]['qty'];
				$product_price = $price->GetPrice($product_ids[$b], false, $product_qty, $tax_class_id, '')+$price->format($_SESSION['cart']->attributes_price($product_ids[$b]), false);
				$product_price *= $product_qty;
				$ajax->assign("price_".$product_ids[$b], "innerHTML", $price->format($product_price, true));
			}
		}

		$ajax->assign($which."_address", "innerHTML", address_label($_SESSION['customer_id'], $_SESSION[$sess], true, ' ', '<br />'));

		if($which == 'shipping' && isset ($_SESSION['credit_covers']))
			$_SESSION['payment'] = 'no_payment';

		if($which == 'shipping') {
			$order = new order();
			$shipping_block = $checkout->getShippingBlock($price);
			$order = new order();
			$order_total_modules = new order_total();
			$order_total_modules->process();
			$payment_modules = new payment();
			$payment_modules->update_status();

			$payment_button = '';
			$payment_button .= str_replace("\n", "", $payment_modules->process_button(true));

			$payment_block = $checkout->getPaymentBlock($price, $payment_modules);
			$form_url = $checkout->getFormUrl();

			$ajax->assign("shippings", "innerHTML", $shipping_block);
			$ajax->assign("payments", "innerHTML",  $payment_block);
			$ajax->script("if($('#btn_shipping_modules').html() == '-') showFromStart('shipping_modules');");
			$ajax->script("if($('#btn_payment_modules').html() == '-') setTimeout(\"showFromStart('payment_modules')\", 650);
							$('#checkout_hiddens').html('$payment_button').show();");
		}

		$ajax->script("$('#".$which."_address_select').hide();
						$('#".$which."_address').show();
						$('#".$which."_address_button_edit').show();
						$('#".$which."_address_button_save').hide();
						$('#loader_".$which."_address').hide();
						$('#checkout').attr('action', '$form_url');
						$('#shipping_module_error').html('');
						$('#payment_module_error').html('');
						showFromStart('".$which."_address');");

		if($which == 'shipping')
			$ajax->assign("checkout_total","innerHTML", $checkout->getTotalBlock($order, $order_total_modules, $price));
	}
	return $ajax;
}

function updateStates($cid, $which) {
	$ajax = new xajaxResponse();

	if(empty($_SESSION['customer_id']))
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");

	else {
		$zones_array = array ();
		$zones = $this->db->db_query("SELECT
											zone_name
										FROM
											".TABLE_ZONES."
										WHERE
											zone_country_id = ".$this->db->db_prepare($cid)."
										ORDER BY
											zone_name");
		while(!$zones->EOF) {
			$zones_array[] = array ('id' => $zones->fields['zone_name'], 'text' => $zones->fields['zone_name']);
			$zones->MoveNext();
		}
		$entry_state = '';
		if(count($zones_array) > 0) {
			$entry_state = draw_pull_down_menuNote(array ('name' => 'state', 'text' => '&nbsp;'. (not_null(ENTRY_STATE_TEXT) ? '<span class="inputRequirement">'.ENTRY_STATE_TEXT.'</span>' : '')), $zones_array);
			$state_stat = 1;

		} else
			$state_stat = 0;

		if($state_stat == 0) {
			$ajax->script("for (var e=0; e<$('#$which').getElementsByTagName('tr').length; e++) {
								if($('#$which').getElementsByTagName('tr')[e].id == 'checkout_states_row') { $('#$which').getElementsByTagName('tr')[e].hide(); break; }
							}");
		} else {
			$ajax->script("for (var e=0; e<$('#$which').getElementsByTagName('tr').length; e++) {
								if($('#$which').getElementsByTagName('tr')[e].id == 'checkout_states_row') { $('#$which').getElementsByTagName('tr')[e].show(); break; }
							}");
		}
		$ajax->script("$('#loader_".substr($which, 5)."').hide();
						for (var e=0; e<$('#$which span').length(); e++) {
							if($('#$which span')[e].id() == 'checkout_states') { $('#$which span')[e].html('".$entry_state."'); break; }
						}");
	}
	return $ajax;
}

function updateAddress($vars, $which) {
	global $db;
	$ajax = new xajaxResponse();
	if(empty($_SESSION['customer_id'])) {
		$ajax->script("window.location.href = '".FILENAME_LOGIN."';");
		
	} else {
		global $checkout;
		global $price;
		global $order;
		global $order_total_modules;
		$error_text = '';

		if($checkout->newAddressPossible()) {
			$vars = $checkout->convertToVars($vars);
			if($which == 'shipping')
				$sess = 'sendto';
			elseif($which == 'payment')
				$sess = 'billto';
			
			require(DIR_WS_CLASSES.'class.input_fields.php');
			$field = new input_fields('create_account', $vars);
			$gender_male = $field->getField('gender', 'm');
      if ($field->error != 'true')	$gender_female = $field->getField('gender', 'f');
			$title = $field->getField('title', '', 'size="6"');
        $error_text .= $field->required;
			$firstname = $field->getField('firstname');
        $error_text .= $field->required;
			$lastname = $field->getField('lastname');
        $error_text .= $field->required;
			$company = $field->getField('company');
        $error_text .= $field->required;
			$street_address = $field->getField('street_address', '', 'size="21" class="create_account_street"');
        $error_text .= $field->required;
			$street_address_num = $field->getField('street_address_num', '', 'size="3" class="create_account_street_num"');
        $error_text .= $field->required;
			$suburb = $field->getField('suburb');
        $error_text .= $field->required;
			$postcode = $field->getField('postcode', '', 'size="5"  class="create_account_postcode"');
        $error_text .= $field->required;
			$city = $field->getField('city', '', 'size="19" class="create_account_city"');
        $error_text .= $field->required;
			$state = $field->getField('state', '', 'class="create_account_state"');
        $error_text .= $field->required;
			$country = $field->getField('country', '', 'class="create_account_state" id="country"');
        $error_text .= $field->required;

			if($field->error != 'true') {
				$sql_data_array = array('customers_id' => $_SESSION['customer_id'],
										'entry_firstname' => (!empty($field->post['title']) ? $field->post['title'].' ' : '' ).$field->post['firstname'],
										'entry_lastname' => $field->post['lastname'],
										'entry_street_address' => $field->post['street_address'].' '.$field->post['street_address_num'],
										'entry_postcode' => $field->post['postcode'],
										'entry_city' => $field->post['city'],
										'entry_country_id' => $field->post['country'],
										'entry_state' => $field->post['state'],
										'entry_suburb' => $field->post['suburb'],
										'address_date_added' => 'NOW()',
										'address_last_modified' => 'NOW()');

				if(!empty($field->post['gender']))
					$sql_data_array['entry_gender'] = $field->post['gender'];
				if(!empty($field->post['company']))
					$sql_data_array['entry_company'] = $field->post['company'];

				$db->db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);

				$_SESSION[$sess] = $db->db_insert_id();
				
				$db->db_query("UPDATE 
									".TABLE_CUSTOMERS_INFO." 
								SET 
									customers_info_date_account_last_modified = NOW() 
								WHERE 
									customers_info_id = '".(int)$_SESSION['customer_id']."'");
				
				if($which == 'shipping') {
					$price = new price($_SESSION['currency'], $_SESSION['customers_status']['customers_status_id']);
					$order = new order();
					$zone_change = false;
					if($_SESSION['delivery_zone'] != $order->delivery['country']['iso_code_2'])
						$zone_change = true;

					$_SESSION['delivery_zone'] = $order->delivery['country']['iso_code_2'];

					if($checkout->isFreeShipping($order, $price))
						$ajax->script("updateBecauseItsFreeShipping();");
					else
						$ajax->script("updateBecauseItsNotFreeShipping();");

					$product_ids = explode(', ',$_SESSION['cart']->get_product_id_list());
					for ($b=0; $b<count($product_ids); $b++) {
						$tax_class_id = $checkout->getTaxID($product_ids[$b]);
						$product_qty = $_SESSION['cart']->contents[$product_ids[$b]]['qty'];
						$product_price = $price->GetPrice($product_ids[$b], $format=false, $product_qty, $tax_class_id, '')+$price->format($_SESSION['cart']->attributes_price($product_ids[$b]), false);
						$product_price *= $product_qty;
						$ajax->assign("price_".$product_ids[$b], "innerHTML", $price->format($product_price, true));
					}
				}

				$ajax->assign($which."_address_error","innerHTML","");
				$ajax->assign($which."_address", "innerHTML", address_label($_SESSION['customer_id'], $_SESSION[$sess], true, ' ', '<br />'));
				if($which == 'shipping' && isset($_SESSION['credit_covers'])) 
					$_SESSION['payment'] = 'no_payment';
					
				if($which == 'shipping') {
					$order = new order();
					$shipping_block = $checkout->getShippingBlock($price);
					$order = new order();
					$order_total_modules = new order_total();
					$order_total_modules->process();
					$payment_modules = new payment();
					$payment_modules->update_status();

					$payment_button = '';
					$payment_button .= str_replace("\n","",$payment_modules->process_button(true));
					$payment_block = $checkout->getPaymentBlock($price, $payment_modules);
					$form_url = $checkout->getFormUrl();
					$ajax->assign("shippings", "innerHTML", $shipping_block);
					$ajax->assign("payments", "innerHTML", $payment_block);
					$ajax->script("if($('#btn_shipping_modules').html()=='-')showFromStart('shipping_modules');");
					$ajax->script("if($('#btn_payment_modules').html()=='-')setTimeout(\"showFromStart('payment_modules')\", 500);
									$('#checkout_hiddens').html('$payment_button').show();");
				}
				$ajax->script("$('#".$which."_address_select').slideToggle();
							  $('#".$which."_address').show();
							  $('#".$which."_address_button_edit').show();
							  $('#".$which."_address_button_save').hide();
							  $('#loader_".$which."_address').hide();
							  $('#shipping_module_error').html('');
							  $('#payment_module_error').html('');
							  $('#checkout').attr('action', '$form_url');
							  showFromStart('".$which."_address');");
				if($which == 'shipping')
					$ajax->assign("checkout_total","innerHTML", $checkout->getTotalBlock($order, $order_total_modules, $price));

			} else {
				$ajax->assign($which."_address_error","innerHTML",$error_text);
				$ajax->script("makeActive('chkt_".$which."_address');
							  $('#loader_".$which."_address').hide();
							  showFromStart('".$which."_address');");
			}
		} else {
			$error_text = '- '.CHECKOUT_NOMORE_ADDRESSES;
			$ajax->assign($which."_address_error","innerHTML",utf8_encode($error_text));
			$ajax->script("$('#loader_".$which."_address').hide(); showFromStart('".$which."_address');");
		}
	}
	return $ajax;
}

if(!is_object($xajax))
	$xajax = new xajax();

$xajax->setRequestURI(href_link(FILENAME_CHECKOUT, '', 'SSL'));
$xajax->registerFunction("updateProducts");
$xajax->registerFunction("updateAttributes");
$xajax->registerFunction("removeProduct");
$xajax->registerFunction("updateAddressSelect");
$xajax->registerFunction("updateAddressBySelect");
$xajax->registerFunction("updateStates");
$xajax->registerFunction("updateAddress");
$xajax->registerFunction("useGV");
$xajax->registerFunction("updatePaymentModule");
$xajax->registerFunction("updateShippingModule");
$xajax->registerFunction("checkout_check");